<template>
  <div class="view-wrapper">
    <div class="tabs-body">
      <div class="view-inner-wrap">
        <div class="title">{{title}}</div>
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="130px" class="demo-ruleForm"
          :disabled="disabled">
          <el-row v-if="startTypeShow">
            <el-col :span="12">
              <el-form-item label="是否启用：" prop="startType">
                <el-switch v-model="ruleForm.startType" active-value="2" inactive-value="1" active-text="启用"
                  inactive-text="关闭">
                </el-switch>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="活动名称：" prop="name">
                <el-input v-model="ruleForm.name" placeholder="请填写活动名称" maxlength="50"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="活动时间：" prop="date">
                <el-date-picker v-model="ruleForm.date" @change="getTime" type="datetimerange"
                  format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH" range-separator="至" start-placeholder="开始日期"
                  end-placeholder="结束日期" placeholder="选择日期时间">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="合成NFR：" prop="castingEquityCardId">
                <el-select v-model="ruleForm.castingEquityCardId" filterable placeholder="请选择"
                  @change="changeCastingEquityCardId" :disabled="editDisabled">
                  <el-option v-for="itema in cardList" :key="itema.equityCardId" :label="itema.equityCardName"
                    :value="itema.equityCardId">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="总数量：" prop="total" required>
                <el-input v-model="ruleForm.total" placeholder="请填写总数量"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="合成材料：" prop="seleMaterialsDTOListId">
                <el-select v-model="ruleForm.seleMaterialsDTOListId" filterable multiple placeholder="请选择"
                  value-key="equityCardId" @change="changeMaterialsDTOList($event)">
                  <el-option v-for="itema in needCardList" :key="itema.equityCardId" :label="itema.equityCardName"
                    :value="itema">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="ruleForm.materialsDTOList.length > 0">
            <el-col :span="15">
              <div style="margin-left: 130px;padding-bottom: 20px">
                <el-table v-loading="loading" :data="ruleForm.materialsDTOList" stripe border>
                  <el-table-column label="序号" type="index" width="55" align="center" fixed />
                  <el-table-column label="材料类型" align="center" prop="materialType" width="200"
                    :show-overflow-tooltip="true">
                    <template slot-scope='scope'>
                      <el-form-item label="" label-width="0"
                        :prop="'materialsDTOList.' + scope.$index + '.materialType'" :rules="rules.materialType">
                        <el-select v-model="scope.row.materialType" filterable placeholder="请选择"
                          @change="$forceUpdate()">
                          <el-option v-for="item in materialTypeList" :key="item.id" :label="item.value"
                            :value="item.id">
                          </el-option>
                        </el-select>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column label="NFR名称" align="center" prop="equityCardName" :show-overflow-tooltip="true" />
                  <el-table-column label="合成所需数量" align="center" prop="amount" width="130">
                    <template slot-scope='scope'>
                      <el-form-item label="" label-width="0" :prop="'materialsDTOList.' + scope.$index + '.amount'"
                        :rules="rules.amount">
                        <el-input placeholder="所需数量" v-model="scope.row.amount" @input="inputClick" />
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column label="增加成功率(%)" align="center" prop="increaseRate" width="240">
                    <template slot-scope='scope' v-if="scope.row.materialType=='2'">
                      <el-form-item label="" label-width="0"
                        :prop="'materialsDTOList.' + scope.$index + '.increaseRate'" :rules="rules.increaseRate">
                        <el-input placeholder="成功率" v-model="scope.row.increaseRate" @input="inputClick">
                          <template slot="append">%</template>
                        </el-input>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" align="center" width="120" class-name="small-padding fixed-width">
                    <template slot-scope="scope">
                      <el-button size="mini" type="text" @click="handleDelete(scope.$index)">
                        删除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>

            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="合成手续费：" prop="serviceFeeType">
                <el-select v-model="ruleForm.serviceFeeType" placeholder="请选择">
                  <el-option v-for="itema in serviceFeeTypeList" :key="itema.id" :label="itema.value" :value="itema.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="ruleForm.serviceFeeType != 1">
            <el-col :span="12">
              <el-form-item label="手续费：" prop="serviceFee">
                <el-input v-model="ruleForm.serviceFee" placeholder="请填写手续费">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="合成成功率：" prop="realSuccessRate">
                <el-input v-model="ruleForm.realSuccessRate"
                  @keyup.native="ruleForm.realSuccessRate = oninput(ruleForm.realSuccessRate)" placeholder="请填写合成成功率">
                  <template slot="append">%</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="虚拟成功率：" prop="successRate">
                <el-input v-model="ruleForm.successRate"
                  @keyup.native="ruleForm.successRate = oninput(ruleForm.successRate)" placeholder="请填写虚拟成功率">
                  <template slot="append">%</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item>
            <el-button type="primary" @click="cancelForm()">取消</el-button>
            <el-button type="primary" @click="submitForm('ruleForm')" :loading="loading">保存提交</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>

  </div>
</template>
<script>
  import {
    cardSelect,
    addActivity,
    castingDetail,
    editCasting,
    materialSelect
  } from '@/api/blindBox/factoryConfig'
  import {
    set
  } from 'js-cookie';
  export default {
    name: "",
    components: {

    },

    data() {
      var validateTotal = (rule, value, callback) => {
        console.log('validateEnd', rule)
        var reg = /^[1-9]+[0-9]*$/
        if (value === '') {
          callback(new Error('请输入总数量'));
        } else if (!reg.test(value)) {
          callback(new Error('请输入整数')); 
        } else {
          callback()
        }
      };
      var validateAmount = (rule, value, callback) => {
        var reg = /^[1-9]+[0-9]*$/
        if (value === '') {
          callback(new Error('请输入所需数量'));
        } else if (!reg.test(value)) {
          callback(new Error('请输入整数'));
        } else {
          callback()
        }
      };
      var validateIncreaseRate = (rule, value, callback) => { //销售原价校验
        let regNumber = /(^[1-9](\d+)?(\.\d{1,2})?$)|(^\d\.\d{1,2}$)/; //大于0的数值且最多保留两位小数的数值
        if (regNumber.test(value) == false || value == '0.00' || value == '0.0') {
          return callback(new Error('请填写大于0且最多保留两位小数的数值'));
        } else {
          return callback()
        }
      };
      return {
        title: '新增合成活动',
        cardList: [],
        needCardList: [],
        serviceFeeTypeList: [{
            id: '1',
            value: '不收手续费',
          },
          {
            id: '2',
            value: '椰分',
          },
          {
            id: '3',
            value: '神椰CoCo',
          },
        ],
        materialTypeList: [{
            id: '1',
            value: '主材料',
          },
          {
            id: '2',
            value: '辅助材料',
          },
        ],
        startTypeShow: true,
        disabled: false,
        editDisabled: false,
        pathType: 'add',
        loading: false,
        ruleForm: {
          castingEquityCardId: '', //合成NFRId
          castingEquityCardName: '', //合成NFR名称
          endTime: '', //活动结束时间
          id: '', //任务类型 1限时打卡 2限时合成 3限时销毁
          materialsDTOList: [ //合成材料数组
            // {
            //   amount: '', //数量
            //   equityCardId: '',
            //   equityCardName: '', //名称
            //   materialType: '', //材料类型 1主材料 2辅助材料
            //   increaseRate: '', //增加成功率
            // }
          ],
          name: '', //活动名称
          realSuccessRate: '', //真实成功率
          serviceFee: '', //手续费
          serviceFeeType: '', //手续费类型 1 不收手续费 2 椰分 3 神椰CoCo
          startTime: '', //活动开始时间
          startType: '2', //	启用类型 1 未启用 2 启用
          successRate: '', //虚拟成功率
          total: '', //总数量
          date: [],
          seleMaterialsDTOListId: [],

        },
        rules: {
          startType: [{
            required: true,
            message: '请选择状态',
            trigger: 'change'
          }, ],
          name: [{
            required: true,
            message: '请输入活动名称',
            trigger: ['blur', 'change']
          }, ],
          date: [{
            required: true,
            message: '请选择日期',
            trigger: 'change'
          }],
          castingEquityCardId: [{
            required: true,
            message: '请选择合成NFR',
            trigger: 'change'
          }, ],
          total: [{
            validator: validateTotal,
            trigger: ['blur', 'change']
          }, ],
          seleMaterialsDTOListId: [{
            required: true,
            message: '请选择合成材料',
            trigger: 'change'
          }, ],
          totalIntegral: [{
            required: true,
            message: '请输入所需数量',
            trigger: ['blur', 'change']
          }, ],
          serviceFeeType: [{
            required: true,
            message: '请选择合成手续费',
            trigger: 'change'
          }, ],
          serviceFee: [{
            required: true,
            message: '请输入手续费',
            trigger: ['blur', 'change']
          }, ],
          realSuccessRate: [{
            required: true,
            message: '请输入成功率',
            trigger: ['blur', 'change']
          }, ],
          successRate: [{
            required: true,
            message: '请输入虚拟成功率',
            trigger: ['blur', 'change']
          }, ],
          amount: [{
            validator: validateAmount,
            trigger: ['blur', 'change']
          }, ],
          materialType: [{
            required: true,
            message: '请选择材料类型',
            trigger: 'change'
          }, ],
          increaseRate: [{
            validator: validateIncreaseRate,
            trigger: ['blur', 'change']
          }, ],
        }

      };
    },
    watch: {

    },
    created() {
      this.pathType = this.$route.query.pathType
      this.ruleForm.id = this.$route.query.id
      this.getCard()
      this.getMaterial()
      if (this.pathType == 'edit') {
        this.title = '编辑合成活动'
        this.getDetail()
      } else if (this.pathType == 'detail') {
        this.title = '查看详情'
        this.getDetail()
        this.disabled = true
      }
    },
    mounted() {

    },
    methods: {
      //获取NFR下拉
      getCard() {
        cardSelect().then(res => {
          this.cardList = res.result
        })
      },
      //获取合成下料
      getMaterial() {
        materialSelect().then(res => {
          this.needCardList = res.result
        })
      },
      //格式化选择时间
      getTime(e) {
        console.log("e", e)
        var timeArr = e
        this.ruleForm.startTime = e[0] + ':00:00'
        this.ruleForm.endTime = e[1] + ':00:00'
        console.log("e", this.ruleForm.startTime)
        console.log("e", this.ruleForm.endTime)
      },
      //获取详情
      getDetail() {
        castingDetail(this.ruleForm.id).then(response => {
          this.ruleForm.castingEquityCardId = response.result.castingEquityCardId
          this.ruleForm.castingEquityCardName = response.result.castingEquityCardName
          this.ruleForm.id = response.result.id
          this.ruleForm.materialsDTOList = response.result.materialsDTOList
          this.ruleForm.name = response.result.name
          this.ruleForm.realSuccessRate = response.result.realSuccessRate
          this.ruleForm.serviceFee = response.result.serviceFee
          this.ruleForm.serviceFeeType = response.result.serviceFeeType
          this.ruleForm.startType = response.result.startType
          this.ruleForm.successRate = response.result.successRate
          this.ruleForm.total = response.result.total
          this.ruleForm.date.push(response.result.startTime)
          this.ruleForm.date.push(response.result.endTime)
          this.ruleForm.startTime = response.result.startTime
          this.ruleForm.endTime = response.result.endTime

          this.ruleForm.seleMaterialsDTOListId = response.result.materialsDTOList
          // this.ruleForm.seleMaterialsDTOListId = JSON.parse(JSON.stringify(response.result.materialsDTOList));

          if (response.result.startType == 2) {
            this.editDisabled = true
          }
          if (this.pathType == 'edit' && response.result.startType == 2) {
            this.startTypeShow = false
          }
          // this.ruleForm.seleMaterialsDTOListId 
          this.needCardList = this.cardList.filter(item => item.equityCardId != this.ruleForm.castingEquityCardId);
        });
      },
      inputClick() { //修复input无法输入问题
        this.$forceUpdate()
      },
      //删除
      handleDelete(index) {
        // this.ruleForm.materialsDTOList.splice(index, 1) //materialsDTOList和seleMaterialsDTOListId已经在获取信息中双向绑定,故这里不需要删除方法,这边也写删除方法会有问题
        this.ruleForm.seleMaterialsDTOListId.splice(index, 1)
      },
      //选择合成ntf
      changeCastingEquityCardId(id) {
        const thisLabel = this.cardList.find(item => item.equityCardId == id).equityCardName
        this.ruleForm.castingEquityCardName = thisLabel
        console.log('thisLabel',thisLabel)
        this.needCardList = this.cardList.filter(item => item.equityCardId != this.ruleForm.castingEquityCardId);
        // console.log('this.needCardList',this.needCardList)
      },
      //选择合成材料
      changeMaterialsDTOList(e) {
        console.log('e++++', e)
        this.ruleForm.materialsDTOList = []
        this.ruleForm.materialsDTOList = e
        console.log(this.ruleForm.materialsDTOList)
        // var array = []
        // e.forEach(item => {
        //   this.cardList.forEach(bItem => {
        //     if (item == bItem.id) {
        //       var obj = {}
        //       obj.amount = ''
        //       obj.equityCardId = bItem.id
        //       obj.equityCardName = bItem.value
        //       // obj.materialType = '' //材料类型 1主材料 2辅助材料
        //       // obj.increaseRate = '' //增加成功率
        //       array.push(obj)
        //     }
        //   })
        //   this.ruleForm.materialsDTOList = array
        //   // console.log(array)
        // })
      },
      // 取消
      cancelForm() {
        this.$router.go(-1)
      },
      submitForm(formName) {
        console.log('data', this.ruleForm)
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.loading = true
            if (this.pathType == 'add') {
              var data = {
                ...this.ruleForm
              }
              console.log('data', data)
              addActivity(data).then(res => {
                this.$message.success('创建成功')
                this.$router.push({
                  path: '/blindBox/factoryConfig-list'
                })
                setTimeout(() => {
                  this.loading = false


                }, 5000);
              }).finally(() => {
                this.loading = false
              })
            } else if (this.pathType == 'edit') {

              var data = {
                ...this.ruleForm
              }
              editCasting(data).then(res => {
                this.$message.success('修改成功')
                this.$router.push({
                  path: '/blindBox/factoryConfig-list'
                })
                setTimeout(() => {
                  this.loading = false


                }, 1000);
              }).finally(() => {
                this.loading = false
              })
            }
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
      handleSuccess(msg) {
        if (msg === '已拒绝') {
          var type = 'error'
        } else {
          var type = 'success'
        }
        this.$message({
          message: msg,
          type: type,
          duration: 1500,
          // onClose: () => {
          //   this.handleClose('ruleForm')
          // }
        })
        this.$router.push({
          path: '/blindBox/timeLimitActivities-List'
        })
      },
      oninput(num) {
        var str = num
        var len1 = str.substr(0, 1)
        var len2 = str.substr(1, 1)
        //如果第一位是0，第二位不是点，就用数字把点替换掉
        if (str.length > 1 && len1 == 0 && len2 != ".") {
          str = str.substr(1, 1)
        }
        //第一位不能是.
        if (len1 == ".") {
          str = ""
        }
        //限制只能输入一个小数点
        if (str.indexOf(".") != -1) {
          var str_ = str.substr(str.indexOf(".") + 1)
          if (str_.indexOf(".") != -1) {
            str = str.substr(0, str.indexOf(".") + str_.indexOf(".") + 1)
          }
        }
        //正则替换
        str = str.replace(/[^\d^\.]+/g, '') // 保留数字和小数点
        str = str.replace(/\.\d\d\d$/, '') // 小数点后只能输两位
        return str
      },

    },
  };

</script>
<style lang="scss" scoped>
  .tabs-body {
    background-color: #fff;
    padding: 20px 0;
  }

  .title {
    font-size: 24px;
    padding: 14px 30px 14px 14px;
    margin-bottom: 14px;
    color: #222;
    font-weight: bold;
    border-bottom: 1px solid #DCDFE6;
  }

  .seleInp .el-select {
    width: 100%;
  }

  .rowList {
    display: flex;
    justify-content: flex-start;

    .el-select {
      width: 130px;
    }
  }

  .inpBox {
    display: flex;
    justify-content: flex-start;
    align-items: center;

    .el-input {
      width: 100px;
    }
  }

  .btnBox {
    width: 100px;
    margin-left: 20px;
  }

  .mar-r-10 {
    margin-right: 14px;

  }

  .txt {
    font-family: Helvetica Neue, Helvetica, PingFang SC, Hiragino Sans GB, Microsoft YaHei, Arial, sans-serif;
    font-weight: 700;
    color: #606266;

  }

  .mar-l-10 {
    margin-left: 14px;
  }

  .disSb {
    display: flex;
    justify-content: space-between;
  }

</style>
